package com.liu.demo;

import com.liu.spring.framework.annotation.Component;
import com.liu.spring.framework.aware.BeanPostProcessor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author LIU
 * @version 1.0
 * @description: TODO
 * @date 2022/8/29 17:59
 */
@Component
public class LiuBeanPostProcessor implements BeanPostProcessor {
    /**
     * bean前置处理
     *
     * @param beanName
     * @param bean
     */
    @Override
    public Object postProcessorBeforeInitialization(String beanName, Object bean) {
        if (beanName.equals("userService")) {
            System.out.println("-----bean前置处理-----");
        }
        return bean;
    }

    @Override
    public Object postProcessorAfterInitialization(String beanName, Object bean) {

        if (beanName.equals("userService")) {
            System.out.println("-----bean后置处理-----");

            //jdk动态代理对象
            Object proxyInstance = Proxy.newProxyInstance(LiuBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("AOP前置切面逻辑");
                    Object invoke = method.invoke(bean, args);
                    System.out.println("AOP后置切面逻辑");
                    return invoke;
                }
            });

            return proxyInstance;
        }

        return bean;
    }
}
